//
//  YTransitionAnimation.swift
//  friends
//
//  Created by xwh on 2021/4/8.
//

import UIKit

enum YTransitionAnimationDirection {
    case present,dismiss
}

class YTransitionAnimation: NSObject, UIViewControllerAnimatedTransitioning {
    
    var transitionDuration:TimeInterval = 0.3
    var animationTime:TimeInterval = 0.25
    var animationFinishedTime:TimeInterval = 0.2

    
    var animationType:YTransitionAnimationDirection = .present
    
    init(type:YTransitionAnimationDirection) {
        self.animationType = type
    }
    
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return transitionDuration
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        
        switch animationType {
        case .present:
            
            if let toVC:YTimePicker = transitionContext.viewController(forKey: .to) as? YTimePicker {
                let toView = toVC.view
                
                let containerView = transitionContext.containerView
                containerView.addSubview(toView!)
                
                toVC.containerView.transform = CGAffineTransform(translationX: 0, y: toVC.containerView.frame.height)
                
                UIView.animate(withDuration: animationTime, delay: 0, options: .curveEaseIn) {
                    toVC.view.alpha = 1.0
                    toVC.containerView.transform = CGAffineTransform(translationX: 0, y: -10)
                    
                } completion: { (result) in
                    
                    UIView.animate(withDuration: self.animationFinishedTime, delay: 0, options: .curveEaseIn) {
                        toVC.containerView.transform = .identity
                        
                    } completion: { (result) in
                        transitionContext.completeTransition(true)
                    }
                    
                }

                
            }
           
            
            
            
            break
        case .dismiss:
            
            if let toVC:YTimePicker = transitionContext.viewController(forKey: .from) as? YTimePicker {
                
                UIView.animate(withDuration: animationTime, delay: 0, options: .curveEaseIn) {
                    toVC.view.alpha = 1.0
                    toVC.containerView.transform = CGAffineTransform(translationX: 0, y: toVC.containerView.frame.height)
                    
                } completion: { (result) in
                    transitionContext.completeTransition(true)
                }
            }
            
            
            
            
            break
        default:break
        }
    }
    

    
}
